import pdb
# from cfg import *
from optparse import OptionParser


parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="read/write session results to FILE", metavar="FILE")
parser.add_option("-u", "--urlpattern", dest="urlpattern",
                  help="URL pattern to use. Use a backslash to indicate each \
                  incrementable part, e.g. enter \
                  'http://domain.com/pics/\/\.jpg' to produce \
                  'http://domain.com/pics/0/0.jpg', \
                  'http://domain.com/pics/0/1.jpg', etc. \
                  If FILE contains a URL pattern, that will take precedence.")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

class targetUrl():
    def __init__():
        # Domain to use in URL:
        domain = ""

        # Characters to use in URL parts:
        char_list = "_-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

        # Number of increments to increase by when jumping intermediates:
        jump_value = 4

        # Using lists, in order to get a bank of mutable "strings".

        # Try permutations from char_list between 10-12 characters long, for parts 1 to 4 of URL.
        # (Except in testing; vary list below to include 
        part_starting_length = 2
        part_starting_state = list(part_starting_length * char_list[0])
        # part_ending_state   = ['z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z']
        part_ending_state = 3 * char_list[len(char_list) - 1]
        part1 = part_starting_state[:]
        part2 = part_starting_state[:]
        part3 = part_starting_state[:]
        part4 = part_starting_state[:]
    



def reached_end(part,end_state):
    """Check whether part has been fully incremented for its length."""
    if ''.join(part[0:len(part)-1]) == end_state[0:len(end_state)-1] and \
       char_list.index(part[len(part) - 1]) > len(char_list) - (jump_value + 1):
        return True
    else:
        return False

def increment(part,jump):
    """Increment the part by one character from char_list or else by 'jump'."""
    if reached_end(part,len(part) * char_list[len(char_list) - 1] ):
        # pdb.set_trace()
        incoming_part_length = len(part)
        part_chars = char_list[0] * (incoming_part_length + 1)
        part = list(part_chars)
    else:
        part_index = len(part) - 1
        while part_index > -1:
            char_index = char_list.index(part[part_index])
            if part_index == len(part) - 1 and jump == True:
                part[part_index] = char_list[(char_index + jump_value) % len(char_list)]
            else:
                part[part_index] = char_list[(char_index + 1) % len(char_list)]
            if char_index == len(char_list) - 1 or \
               ((part_index == len(part) - 1 and jump == True) and \
               len(char_list) - char_index <= jump_value):
                part_index = part_index - 1
            else:
                part_index = -1
    return part

def check_result():
    """Determine the URL resulting from the latest increment, and use it."""
    result = 'http://' + domain + '/' + ''.join(part1) + '/' + ''.join(part2) + \
       '/' + ''.join(part3) + '/' + ''.join(part4) + '/'
    print result


def obtain_urlpattern():
    """Obtain a urlpattern to use; check it won't go over 255 chars."""
    if options.filename:
        f = open(options.filename, 'r+')
        if re.match(f.readline(), 'urlpattern'):
            print "yay!"
        else if options.urlpattern:
            f.write(options.urlpattern)
    else if options.urlpattern:
        print "yoo!"
    else:
        exit("No URLPATTERN")


def main():
    obtain_urlpattern()
    parse_urlpattern()
    """Generate each desired URL in turn, and check it."""
    global part1
    global part2
    global part3
    global part4
    while not ''.join(part1) == part_ending_state:
        while not reached_end(part2,part_ending_state):
            while not reached_end(part3,part_ending_state):
                while not reached_end(part4,part_ending_state):
                    check_result()
                    part4 = increment(part4,True)
                check_result()
                # exit('End!')
                part4 = part_starting_state[:]
                increment(part3,True)
            check_result()
            # exit('End!')
            part3 = part_starting_state[:]
            increment(part2,True)
        check_result()
        # exit('End!')
        part2 = part_starting_state[:]
        increment(part1,False)



if __name__ == "__main__":
    main()
